package com.by.toolkit.utils;

import cn.hutool.core.map.MapUtil;
import com.by.toolkit.consts.GlobalConst;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * url公共方法
 */
public class UrlUtil {

    public static String getUrlParam(String url, String name) {
        Map<String, String> split = null;
        try {
            String params = url.substring(url.indexOf("?") + 1);
            split = Splitter.on("&").withKeyValueSeparator("=").split(params);
            return split.get(name);
        } catch (Exception e) {
            return StringUtils.EMPTY;
        }
    }

    public static Map<String, String> getUrlParam(String url) {
        int index = url.indexOf("?");
        String param = url.substring(index + 1);
        String[] params = param.split("&");
        Map<String, String> map = new HashMap<>();
        for (String item : params) {
            String[] kv = item.split("=");
            if (kv.length == 1) {
                continue;
            }
            map.put(kv[0], kv[1]);
        }
        return map;
    }

    public static String map2UrlParam(Map<String, Object> param) {
        return map2UrlParam(param, true);
    }

    public static String map2UrlParam(Map<String, Object> param, boolean isIgnoreNull) {
        return MapUtil.join(param, "&", "=", isIgnoreNull);
    }

    public static String httpUrlAppendParam(String httpUrl, Map<String, Object> param) {
        return httpUrlAppendParam(httpUrl, param, true);
    }

    public static String httpUrlAppendParam(String httpUrl, Map<String, Object> param, boolean isIgnoreNull) {
        if (StringUtils.isBlank(httpUrl)) {
            return httpUrl;
        }
        String urlParam = map2UrlParam(param, isIgnoreNull);
        if (StringUtils.isBlank(urlParam)) {
            return httpUrl;
        }
        return httpUrl + (httpUrl.indexOf("?") > GlobalConst.NEGATIVE_ONE_INTEGER ? "&" : "?") + urlParam;
    }

}